<?php

/**
 * @Author: Ron Chen
 * @Date:   2017-03-26 15:55:37
 * @Last Modified by:   Ron Chen
 * @Last Modified time: 2017-07-18 22:34:24
 */

namespace app\controllers;

use Yii;
use yii\web\Response;
use app\models\InsurancePolicy;
use app\models\InsurancePolicyReturn;
use app\models\InsurancePrice;
use app\models\InsurancePolicyInsured;
use app\models\InsurancePolicyHolder;
use app\services\PayServices;
use app\services\PolicyServices;

/**
 *
 * @name 购买信息填写
 *
 */
class PayController extends BaseController
{
    public $enableCsrfValidation = false;

    public function init()
    {
        parent::init();
        $this->layout = "insurance-buy";
    }

    public function actionOrder()
    {
        $order_id = trim($this->request->get('id', ''));
        $pay_service = new PayServices ();

        $policy_detail = InsurancePolicy::findOne($order_id);
        if (!$policy_detail) {
            return $this->redirect(['/index/list']);
        }
        // 是否已经生成保单
        $message = "";
        $policyRef = $policy_detail->policy_id;
        if (empty($policyRef)) {
            $policy_info = new PolicyServices();
            $data = $policy_info->addPolicyOrder($order_id);
            $xml_data = simplexml_load_string($data);
            $message = "";
            $policyRef = "";
            if ($xml_data->Head->ResponseCode && $xml_data->Head->ErrorCode == '0000') {
                // 更新保单号
                $policyRef = $xml_data->Body->PolicyRef;
                $policy_detail->policy_id = $policyRef;
                $policy_detail->desc = json_encode([
                    "PolicyRef" => $policyRef,
                    "AgencyPolicyRef" => $xml_data->Body->AgencyPolicyRef,
                    "PolicyStatus" => $xml_data->Body->PolicyStatus,
                    "TotalPremium" => $xml_data->Body->TotalPremium,
                ]);
                $policy_detail->save();
            } else {
                $message = $xml_data->Head->ErrorMessage;
            }
        }

        return $this->render('order', [
            "message" => $message,
            "title" => $policy_detail->project_name,
            "PayUrl" => PayServices::PAY_SERVICE_URL,
            "data" => $pay_service->sendRequest($policy_detail->premium_total, $policyRef),
        ]);
    }

    /**
     * 异步回调通知
     */
    public function actionNotifyOrder()
    {
        // 外网能访问的地址
        Yii::$app->response->format = Response::FORMAT_JSON;
        $file_name = Yii::$app->basePath . sprintf("/web/logs/%s.log", date("YmdHis"));
        file_put_contents($file_name, json_encode($this->request->post()) . PHP_EOL, FILE_APPEND);
        return [
            "code" => '0',
            "message" => 'success'
        ];
    }


    /**
     * 实时通知地址
     */
    public function actionReturnOrder()
    {
        $params = $this->request->post();
        $file_name = Yii::$app->basePath . sprintf("/web/logs/%s.log", date("YmdHis"));
        file_put_contents($file_name, json_encode($params) . PHP_EOL, FILE_APPEND);
        // 回调信息存储
        $model = new InsurancePolicyReturn();
        $model->policy_ref = $params['policyRef'] ? $params['policyRef'] : "";
        $model->trade_status = $params['tradeStatus'] ? $params['tradeStatus'] : "";
        if (!empty($params)) {
            $model->json = json_encode($params);
        }
        $model->created_at = time();
        $model->updated_at = time();
        $model->save();

        // 请求一下api.funfind.cn把消息传递给用户

        parent::postResponseHandle(PayServices::ORDER_NEWS_PUSH_URL, $params);
        if ($params && isset($params["tradeStatus"]) && $params["tradeStatus"] == 'SUCCESS') {
            // 支付成功
            $data = PolicyServices::getPolicyInfo($params['policyRef']);//投保结果分享页所需数据
            //保单支付时间
            $policy_id = $params['policyRef'];
            $pay_time = $params['payTime'];
            $insurancePolicy = InsurancePolicy::find()->where(['policy_id' => $policy_id])->limit(1)->one();
            $insurancePolicy->pay_time = $pay_time;
            $insurancePolicy->save();
            //请求邀请订单接口
            $state = InsurancePolicy::PAYMENT;
            $token = InsurancePolicy::TOKEN;
            $url = InsurancePolicy::INVITE_ORDER."?id=$user_id&policy_id=$policy_id&state=$state&token=$token";
            $invite = file_get_contents($url);
            return $this->render('result', [
                "code" => 0,
                "data" => $data
            ]);
        } else {
            // 支付失败
            return $this->render('result', [
                "code" => -1,
                "message" => $params["msg"],
            ]);
        }
    }

    public function actionTest()
    {
        $policyRef = '201-1-594-18-0000198089-00';
        $data = PolicyServices::getPolicyInfo($policyRef);
        return $this->render('result', [
            "code" => 0,
            "data" => $data
        ]);
    }

    /**
     * 支付成功
     */
    public function actionPaySuccess()
    {
        return $this->render('pay-success', [
            "code" => -1,
        ]);
    }

    /**
     * 支付分享
     */
    public function actionShare()
    {
        return $this->render('share', [
            "code" => -1,
        ]);
    }


}